<script setup lang="ts" name="ProcessVariables">
import { mapState } from 'pinia'
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import { getProcessVariablesList, isProcessVariablesSupported } from '../../utils/processVariables'
import EventEmitter from '@/utils/EventEmitter'

const mapStates = computed(() => {
  return mapState(useModelerStore, ['getActive'])
})

const processVariablesList: any = ref([])

const initData = async () => {
  processVariablesList.value = await getProcessVariablesList(mapStates.value.getActive())
  console.log(processVariablesList.value, '获取变量数据')
}

const eventEmitterListener = () => {
  if (isProcessVariablesSupported(mapStates.value.getActive())) {
    initData()
  }
}

onBeforeUnmount(() => {
  EventEmitter.removeListener('element-update', eventEmitterListener)
})

onMounted(() => {
  initData()
  EventEmitter.on('element-update', eventEmitterListener)
})
</script>

<template>
  <el-collapse-item v-if="processVariablesList.length > 0" name="process-variables">
    <template #title>
      <div class="collapse-header">
        <svg-icon icon="ri:survey-fill"></svg-icon>
        <h2>流程变量</h2>
        <el-button type="primary" size="small" plain circle>{{ processVariablesList.length }}</el-button>
      </div>
    </template>
    <el-form-item>
      <el-table :data="processVariablesList" border>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="name" label="变量名" />
        <el-table-column prop="origin" label="创建节点">
          <template #default="scope">
            <el-tag v-for="item, index in scope.row.origin" :key="index">{{ item }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
  </el-collapse-item>
</template>

<style scoped lang="scss">
.el-collapse-item {
  :deep(.el-collapse-item__header) {

    .collapse-header {
      display: flex;
      flex: 1;
      align-items: center;
      padding: 0 12px;

      .el-icon {
        margin-right: 6px;
        font-size: 20px !important;
      }

      h2 {
        display: flex;
        flex: 1;
        justify-content: flex-start;
        font-weight: bold;
        font-size: 14px;
      }

      .el-button {
        margin-left: 12px;
      }
    }

    .el-icon {
      font-size: 18px;
    }
  }

  :deep(.el-collapse-item__content) {
    padding-right: 12px;
    padding-bottom: 12px;
    padding-left: 12px;
  }
}

.el-form-item {
  :deep(.el-form-item__content) {
    margin-left: 0 !important;

    .el-button.add {
      width: 100%;
      margin: 12px 0 0;
    }
  }
}

.el-tag {
  margin: 2px;
}
</style>
